package com.zheng.demo.producer;

import org.apache.kafka.clients.producer.*;

import java.util.HashMap;
import java.util.Map;

public class KafkaProducerCallBack {
    public static void main(String[] args) {
        Map<String, Object> configMap = new HashMap<>();
        configMap.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        configMap.put(
                ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringSerializer");
        configMap.put(
                ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringSerializer");
        KafkaProducer<String, String> producer = new KafkaProducer<>(configMap);

        // TODO 准备数据,定义泛型
        //    构造对象时需要传递 【Topic主题名称】，【Key】，【Value】三个参数
        for (int i = 0; i < 10; i++) {
            // 创建数据
            ProducerRecord<String, String> record = new ProducerRecord<String, String>(
                    "test", "key1", "value1"
            );
            //  生产（发送）数据
            producer.send(record, new Callback() {
                @Override
                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                    // 数据发送成功，回调此方法
                    System.out.println("回调onCompletion");
                }
            });
        }
        producer.close();
    }
}
